﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.ServiceModel;
using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.Logging;
using Microsoft.Practices.Unity;
using Utility;
using Interfaces;
using Services;

namespace Models
{
    public class ChartModel : BindableBase, IChartModel
    {
        public IChartResults Results { get { return _results; } private set { SetProperty(ref _results, value); } }
        public string Header { get { return _header; } private set { SetProperty(ref _header, value); } }
        public string Ticker { get { return _ticker; } set { SetProperty(ref _ticker, value);} }
        public string Period { get { return _period; } set { SetProperty(ref _period, value); } }
        public string Days { get { return _days; } set { SetProperty(ref _days, value); } }
    
        private readonly IUnityContainer _container;
        private readonly ILoggerFacade _logger;
        private IChartResults _results;
        private string _ticker = "IBM", _period = "300", _days = "1", _header;
    
        public ChartModel(ILoggerFacade logger, IUnityContainer container)
        {
            _logger = logger;
            _container = container;
            GetService();
        }

        public void GetService()
        {
            try
            {
                var factory = new ChannelFactory<IChartResultsService>(new NetNamedPipeBinding(), "net.pipe://localhost/ChartResultsService");
                var _service = factory.CreateChannel();
                
                ICommunicationObject comobj = (ICommunicationObject) _service;
                if (comobj.State != CommunicationState.Faulted)
                {
                    Results = _service.GetResults(_ticker, _period, _days);
                    Header = string.Format("Ticker {0} ({1}), Period {2}, Days {3}, Open {4}, High {5}, Low {6}, Close {7}, Vol {8}", _ticker, _results.Exchange, _period, _days, _results.Sum.Open, _results.Sum.High, _results.Sum.Low, _results.Sum.Close, _results.Sum.Volume);
                }
            }
            catch (Exception e)
            {

            }
        }
    }
}
